package com.ruicar.afs.cloud.basic.proceeds.debit.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.basic.common.entity.BasicCarDetails;
import com.ruicar.afs.cloud.basic.common.entity.BasicMainInfo;
import com.ruicar.afs.cloud.basic.common.service.BasicCarDetailsService;
import com.ruicar.afs.cloud.basic.common.service.BasicDebitInfoService;
import com.ruicar.afs.cloud.basic.common.service.BasicMainInfoService;
import com.ruicar.afs.cloud.basic.proceeds.debit.condition.DebitBatchCondition;
import com.ruicar.afs.cloud.basic.proceeds.debit.entity.*;
import com.ruicar.afs.cloud.basic.proceeds.debit.mapper.BasicDebitBatchMapper;
import com.ruicar.afs.cloud.basic.proceeds.debit.mapper.BasicDebitRecordMapper;
import com.ruicar.afs.cloud.basic.proceeds.debit.service.*;
import com.ruicar.afs.cloud.basic.proceeds.debit.service.impl.thread.ProduceDebitBatchThread;
import com.ruicar.afs.cloud.basic.proceeds.debit.service.impl.thread.ThreadPool;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.uid.AfsSequenceGenerator;
import com.ruicar.afs.cloud.common.modules.contract.enums.*;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.components.datadicsync.DicHelper;
import com.ruicar.afs.cloud.components.datadicsync.dto.DicDataDto;
import com.ruicar.afs.cloud.easypass.enums.RsponseStatusEnum;
import com.ruicar.afs.cloud.easypass.process.config.EasypassConfig;
import com.ruicar.afs.cloud.easypass.process.dto.EasypassRsponseBean;
import com.ruicar.afs.cloud.easypass.process.dto.RecBatchApplyDTO;
import com.ruicar.afs.cloud.easypass.process.dto.RecResultQryDTO;
import com.ruicar.afs.cloud.easypass.process.service.IEasypassProcessService;
import com.ruicar.afs.cloud.manage.api.feign.cust.CustChangeFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;


/**
 * @author: Lee
 * @date 2020-05-30 04:35:07 
 * @description 
 */
@Service
@Slf4j
public class BasicDebitBatchServiceImpl extends ServiceImpl<BasicDebitBatchMapper, BasicDebitBatch> implements BasicDebitBatchService {
    @Autowired
    private BasicDebitRecordService basicDebitRecordService;
    @Autowired
    private BasicDebitBatchDetailsService basicDebitBatchDetailsService;
    @Autowired
    private BasicMainInfoService basicMainInfoService;
    @Autowired
    private AfsSequenceGenerator afsSequenceGenerator;
    @Autowired
    private BasicDebitInterfaceRecordService basicDebitInterfaceRecordService;
    @Autowired
    private BasicDebitHistoryService basicDebitHistoryService;
    @Autowired
    private BasicDebitRecordMapper basicDebitRecordMapper;
    @Autowired
    private IEasypassProcessService iEasypassProcessService;
    @Autowired
    private BasicDebitRecordHistoryServiceImpl basicDebitRecordHistoryService;
    @Autowired
    private BasicDebitInfoService basicDebitInfoService;
    @Autowired
    private BasicCarDetailsService basicCarDetailsService;
    @Autowired
    private CustChangeFeign custChangeFeign;
    @Autowired
    private EasypassConfig config;

    /**
     *
     * <p>Description: 扣款批次明细数据结构化处理</p>
     * @author ZC.GUO
     * @param
     * @return
     */
    private Map<String,List<BasicDebitBatchDetails>> dealDebitDetailList(List<BasicDebitBatchDetails> basicDebitBatchDetailsList){

        Map<String,List<BasicDebitBatchDetails>> batchDetailMap = new HashMap<>(16);
        if (CollectionUtils.isNotEmpty(basicDebitBatchDetailsList)){

            for (BasicDebitBatchDetails batchDetails : basicDebitBatchDetailsList) {
                List<BasicDebitBatchDetails> batchDetailsList;

                if (batchDetailMap.containsKey(batchDetails.getDebitSignBank())){
                    batchDetailsList = batchDetailMap.get(batchDetails.getDebitSignBank());
                }else {
                    batchDetailsList = new ArrayList<>();
                }
                batchDetailsList.add(batchDetails);
                batchDetailMap.put(batchDetails.getDebitSignBank(),batchDetailsList);
            }

        }

        return  batchDetailMap;
    }

    /**
     *
     * <p>Description: 批次明细汇总为批次</p>
     * @author ZC.GUO
     * @param batchDetailMap
     * @return
     */
    private List<BasicDebitBatch> summaryBatch(Map<String,List<BasicDebitBatchDetails>> batchDetailMap){

        List<BasicDebitBatch> debitBatchList = new ArrayList<>();

        if(CollectionUtils.isNotEmpty(batchDetailMap)){
            Iterator<String> debitBanks = batchDetailMap.keySet().iterator();
            while (debitBanks.hasNext()){
                /**  对同一个扣款行下的批次明细进行汇总为批次 by ZC.GUO  **/
                List<BasicDebitBatchDetails> batchDetailsList = batchDetailMap.get(debitBanks.next());
                if (CollectionUtils.isNotEmpty(batchDetailsList)){
                    BasicDebitBatch debitBatch = null;
                    for (BasicDebitBatchDetails batchDetails : batchDetailsList) {
                        if(ObjectUtils.isEmpty(debitBatch)){
                            /**  初始化 by ZC.GUO  **/
                            debitBatch = new BasicDebitBatch();
                            debitBatch = this.initBatch(debitBatch,batchDetails);
                            /**  保存以确定批次id by ZC.GUO  **/
                            this.save(debitBatch);
                        }else {
                            /**  若批次总数达到100，则生成新的批次 by ZC.GUO  **/
                            /**  TODO ZC.GUO 确认批量收款最大扣款笔数是否需要使用配置信息  **/
                            if(debitBatch.getCount() >= 100){
                                /**  旧的批次 by ZC.GUO  **/
                                BasicDebitBatch oldDebitBatch = debitBatch;
                                debitBatchList.add(oldDebitBatch);
                                /**  新的批次初始化 by ZC.GUO  **/
                                debitBatch = new BasicDebitBatch();
                                debitBatch = this.initBatch(debitBatch,batchDetails);
                                /**  保存以确定批次id by ZC.GUO  **/
                                this.save(debitBatch);
                            }
                        }
                        /**  更新批次信息 by ZC.GUO  **/
                        debitBatch = this.updateBatch(debitBatch,batchDetails);

                        /**  id返写 by ZC.GUO  **/
                        batchDetails.setBatchId(debitBatch.getId());
                    }
                    debitBatchList.add(debitBatch);
                }
            }
        }
        return debitBatchList;
    }


    /**
     *
     * <p>Description: 待扣款数据结构化处理</p>
     * @author ZC.GUO
     * @param
     * @return
     */
    private Map<String,List<BasicDebitRecord>> dealDebitRecordList(List<BasicDebitRecord> basicDebitRecordList){

        Map<String,List<BasicDebitRecord>> debitRecordMap = new HashMap<>(16);
        if (CollectionUtils.isNotEmpty(basicDebitRecordList)){

            for (BasicDebitRecord debitRecord : basicDebitRecordList) {
                List<BasicDebitRecord> debitRecordList;

                if (debitRecordMap.containsKey(debitRecord.getContractNo())){
                    debitRecordList = debitRecordMap.get(debitRecord.getContractNo());
                }else{
                    debitRecordList = new ArrayList<>();
                }
                debitRecordList.add(debitRecord);
                debitRecordMap.put(debitRecord.getContractNo(),debitRecordList);
            }
        }
        return  debitRecordMap;
    }
    
    /**
     *
     * <p>Description: 待扣款数据汇总为扣款批次明细</p>
     * @author ZC.GUO
     * @param
     * @return
     */
    private List<BasicDebitBatchDetails> summaryBatchDetail(Map<String,List<BasicDebitRecord>> debitRecordMap, Date batchDate){

        List<BasicDebitBatchDetails> debitBatchDetailsList = new ArrayList<>();

        if(CollectionUtils.isNotEmpty(debitRecordMap)){
            List<String> needDeleteContractList = new ArrayList<>();
            Iterator<String> contractNos = debitRecordMap.keySet().iterator();
            while (contractNos.hasNext()){
                /**  同一个合同下的待扣款数据汇总为一条明细 by ZC.GUO  **/
                String contractNo = contractNos.next();
                List<BasicDebitRecord> debitRecordList = debitRecordMap.get(contractNo);
                if (CollectionUtils.isNotEmpty(debitRecordList)){
                    /**  汇总为明细前进行处理（是否应该进行扣款） by ZC.GUO  **/
                    debitRecordList = this.dealRecordListBeforeSummary(debitRecordList,contractNo,batchDate);

                    /**  经过处理后，存在可打包的指令 by ZC.GUO  **/
                    if (EmptyUtils.isNotEmpty(debitRecordList)){
                        BasicDebitBatchDetails debitBatchDetails = null;
                        for (BasicDebitRecord debitRecord : debitRecordList) {
                            if(ObjectUtils.isEmpty(debitBatchDetails)){
                                /**  初始化 by ZC.GUO  **/
                                debitBatchDetails = new BasicDebitBatchDetails();
                                debitBatchDetails = this.initBatchDetail(debitBatchDetails,debitRecord);
                            }
                            /**  更新 by ZC.GUO  **/
                            debitBatchDetails = this.updateBatchDetail(debitBatchDetails,debitRecord);
                        }
                        debitBatchDetailsList.add(debitBatchDetails);
                    }else{
                        needDeleteContractList.add(contractNo);
                    }
                }
            }
            /**  没有扣款的去掉 by ZC.GUO  **/
            if (EmptyUtils.isNotEmpty(needDeleteContractList)){
                needDeleteContractList.forEach(contractNo ->{
                    debitRecordMap.remove(contractNo);
                });
            }
        }
        return debitBatchDetailsList;
    }

    private List<BasicDebitRecord> dealRecordListBeforeSummary(List<BasicDebitRecord> debitRecordList,String contractNo, Date batchDate){
        BasicDebitRecord preRecord = null;
        for (BasicDebitRecord debitRecord : debitRecordList) {
            if (FeeTypeEnum.advanceSettle.equals(debitRecord.getFeeType())){
                preRecord = debitRecord;
            }
        }
        /**  有提前结清指令 by ZC.GUO  **/
        if (EmptyUtils.isNotEmpty(preRecord)){
            debitRecordList.clear();
            BasicMainInfo mainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>query().lambda()
                    .eq(BasicMainInfo::getContractNo,preRecord.getContractNo())
                    .eq(BasicMainInfo::getContractStatus,ContractStatusEnum.advanceSettle)
            );
            /**  本合同未提前结清，提前结清扣款指令单独打包，否则任何指令都不打包（不进行多余处理） by ZC.GUO  **/
            if (EmptyUtils.isEmpty(mainInfo)){
                debitRecordList.add(preRecord);
            }
        }
        /**  无提前结清指令 by ZC.GUO  **/
        else{
            BigDecimal arrears = basicDebitInfoService.getCurrentArrears(contractNo,batchDate);
            /**  合同无欠款，所有指令不可打包，否则可正常打包（不进行多余处理） by ZC.GUO  **/
            if (arrears.compareTo(BigDecimal.ZERO)<=0){
                debitRecordList.clear();
            }
        }
        return  debitRecordList;
    };

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized Integer generateDebitBatch(Date batchDate) throws ExecutionException, InterruptedException {
        /**  查询所有扣款银行  **/
        log.info("开始全量生成扣款批次");
        Integer batchNum = 0;
        Map<String,List<String>> bankContractNo = new Hashtable<>();
        List<String> debitSignBankList = basicDebitRecordMapper.selectDebitSignBank(DebitStatusEnum.mayDebit);
        if(debitSignBankList != null && debitSignBankList.size()>0){
            /**  固定数据集合 by ZC.GUO  **/
            for (String debitSignBank:debitSignBankList){
                List<String> contractNoList = basicDebitRecordMapper.selectContractNoByBank(debitSignBank,DebitStatusEnum.mayDebit);
                if(contractNoList != null && contractNoList.size()>0){
                    bankContractNo.put(debitSignBank,contractNoList);
                }
            }
            List<Future<Integer>> listFuture = new ArrayList<>();
            for (String debitSignBank:debitSignBankList){
                List<String> contractNoList = bankContractNo.get(debitSignBank);
                if(contractNoList != null && contractNoList.size()>0){
                    listFuture.addAll(this.generateDebitBatchByContracts(bankContractNo,contractNoList,debitSignBank,batchDate));
                }
            }

            /**  判断全部扣款批次生成完毕 by ZC.GUO  **/
            boolean flag = false;

            point: while (!flag) {
                batchNum = 0;
                for (int j = 0; j < listFuture.size(); j++) {
                    Future<Integer> future = listFuture.get(j);
                    if (!future.isDone()) {
                        try {
                            Thread.sleep(1000L);
                        } catch (InterruptedException e) {
                            log.error(e.getMessage());
                        }
                        continue point;
                    }
                    batchNum = batchNum + future.get();
                }
                flag = true;
            }
        }
        log.info("全量生成扣款批次结束，共生成{}个批次",batchNum);
        return batchNum;
    }
    
    /**
     * 根据合同号多线程生成扣款批次
     * @author ZC.GUO
     * @param 
     * @return 
     */
    private List<Future<Integer>> generateDebitBatchByContracts(Map<String,List<String>> bankContractNo,List<String> contractNoList,String debitSignBank, Date batchDate){
        /**  每300个合同开启一条线程 by ZC.GUO  **/
        int threadSize = 300;
        /**  总合同数 by ZC.GUO  **/
        int dataSize = bankContractNo.get(debitSignBank).size();
        /**  线程数 by ZC.GUO  **/
        int threadNum = dataSize / threadSize + 1;

        /**  定义标记,过滤threadNum为整数 by ZC.GUO  **/
        boolean special = dataSize % threadSize == 0;

        /**  初始化线程池 by ZC.GUO  **/
        ThreadPool threadPool = ThreadPool.getThreadPool("generateBatch"+debitSignBank, 35);

        log.info("开始生成扣款批次，扣款银行代码为：{}",debitSignBank);
        List<Future<Integer>> listFuture = new ArrayList<>();
        for (int i = 0; i < threadNum; i++) {
            ProduceDebitBatchThread produceDebitBatchThread = null;
            if (i == threadNum - 1) {
                if (special) {
                    break;
                }
                produceDebitBatchThread = new ProduceDebitBatchThread(bankContractNo,debitSignBank,threadSize * i, dataSize,this,basicDebitRecordService,batchDate);
            } else {
                produceDebitBatchThread = new ProduceDebitBatchThread(bankContractNo,debitSignBank,threadSize * i, threadSize * (i + 1),this,basicDebitRecordService,batchDate);
            }
            Future<Integer> future = threadPool.callProcess(produceDebitBatchThread);
            listFuture.add(future);
        }
        log.info("生成扣款批次结束，扣款银行代码为：{}",debitSignBank);
        return listFuture;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer generateDebitBatchByCondition(DebitBatchCondition debitBatchCondition, Date batchDate){

        /**  查询所有符合查询条件的待扣款数据  **/
        List<BasicDebitRecord> basicDebitRecordList = basicDebitRecordService.list(Wrappers.<BasicDebitRecord>query().lambda()
                .eq(BasicDebitRecord::getDebitStatus,DebitStatusEnum.mayDebit)
                /**  扣款银行 by ZC.GUO  **/
                .eq(ObjectUtils.isNotEmpty(debitBatchCondition.getGenerateBank()),BasicDebitRecord::getDebitSignBank,debitBatchCondition.getGenerateBank())
                /**  合同编号 by ZC.GUO  **/
                .eq(ObjectUtils.isNotEmpty(debitBatchCondition.getContractNo()),BasicDebitRecord::getContractNo,debitBatchCondition.getContractNo())
        );

        return this.generateDebitBatchByList(basicDebitRecordList,batchDate);
    }

    private BasicDebitBatch summaryBatchForSingleDebitWhenDownGrade(List<BasicDebitRecord> debitRecordList,BasicDebitRecord debitRecord){
        /**  扣款金额降档 by ZC.GUO  **/
        List<BasicDebitRecord> recordList = basicDebitRecordService.handleRecordListWhenDownGrade(debitRecordList,debitRecord);

        /**  生成批次明细 by ZC.GUO  **/
        BasicDebitBatchDetails basicDebitBatchDetails = this.generateBatchDetailForOneContract(recordList);

        /**  生成批次 by ZC.GUO  **/
        BasicDebitBatch debitBatch = new BasicDebitBatch();
        debitBatch = this.initBatch(debitBatch,basicDebitBatchDetails);

        /**  批次扣款笔数 by ZC.GUO  **/
        debitBatch.setCount(debitBatch.getCount() + 1);
        /**  批次扣款总额  **/
        debitBatch.setAmount(debitBatch.getAmount().add(basicDebitBatchDetails.getAmount()));

        /**  保存批次 by ZC.GUO  **/
        this.save(debitBatch);

        /**  保存批次明细 by ZC.GUO  **/
        basicDebitBatchDetails.setBatchId(debitBatch.getId());
        basicDebitBatchDetailsService.save(basicDebitBatchDetails);

        for(BasicDebitRecord basicDebitRecord:recordList){
            basicDebitRecord.setBatchId(debitBatch.getId());
            /**  使用乐观锁更新数据  **/
            basicDebitRecordService.updateDebitRecordPrepare(basicDebitRecord);
        }

        /**  发送扣款 by ZC.GUO  **/
        this.sendDebitBatch(debitBatch, DebitModeEnum.manual);
        return debitBatch;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean generateBatchAndSendByContractNo(String contractNo, Date batchDate) {
        boolean flag = false;
        /**  待扣款明细 by ZC.GUO  **/
        List<BasicDebitRecord> debitRecordList = basicDebitRecordService.list(Wrappers.<BasicDebitRecord>query().lambda()
                .eq(BasicDebitRecord::getContractNo,contractNo)
                .eq(BasicDebitRecord::getDebitStatus, DebitStatusEnum.mayDebit)
                .isNull(BasicDebitRecord::getBatchId)
        );

        if (CollectionUtils.isNotEmpty(debitRecordList)){
            /**  合同扣款相关信息，非真实的扣款明细 by ZC.GUO  **/
            BasicDebitRecord debitRecord = basicDebitRecordService.selectAmountAndTimeByContractNo(contractNo);
            if (ObjectUtils.isNotEmpty(debitRecord)){
                /**  TODO ZC.GUO  从系统参数总获取可配置的逾期天数 **/
                int overdueDays = 90;

                if (debitRecord.getOverdueDays()>overdueDays){

                    BasicDebitBatch debitBatch = this.summaryBatchForSingleDebitWhenDownGrade(debitRecordList,debitRecord);
                    /**  发送扣款 by ZC.GUO  **/
                    this.sendDebitBatch(debitBatch,DebitModeEnum.manual);
                }else{
                    List<BasicDebitBatch> debitBatchList = this.generateDebitBatch(debitRecordList,batchDate);

                    for (BasicDebitBatch debitBatch:debitBatchList){
                        /**  手动扣款 by ZC.GUO  **/
                        this.sendDebitBatch(debitBatch,DebitModeEnum.manual);
                    }
                }
                flag = true;
            }
        }
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendAllBatch() {
        List<BatchStatusEnum> batchStatusEnumList = new ArrayList<>();
        batchStatusEnumList.add(BatchStatusEnum.WAIT_SEND);
        batchStatusEnumList.add(BatchStatusEnum.FAIL_SEND);
        List<BasicDebitBatch> debitBatchList = this.list(Wrappers.<BasicDebitBatch>query().lambda()
                .in(BasicDebitBatch::getBatchStatus,batchStatusEnumList)
        );
        if (EmptyUtils.isNotEmpty(debitBatchList)){
            for (BasicDebitBatch debitBatch:debitBatchList){
                this.sendDebitBatch(debitBatch,DebitModeEnum.auto);
            }
        }
    }

    private BasicDebitBatchDetails generateBatchDetailForOneContract(List<BasicDebitRecord> basicDebitRecordList){
        BasicDebitBatchDetails basicDebitBatchDetails = null;
        if (CollectionUtils.isNotEmpty(basicDebitRecordList)){
            for (BasicDebitRecord debitRecord : basicDebitRecordList) {
                if(ObjectUtils.isEmpty(basicDebitBatchDetails)){
                    /**  初始化 by ZC.GUO  **/
                    basicDebitBatchDetails = new BasicDebitBatchDetails();
                    basicDebitBatchDetails = this.initBatchDetail(basicDebitBatchDetails,debitRecord);
                }
                /**  更新 by ZC.GUO  **/
                basicDebitBatchDetails.setAmount(basicDebitBatchDetails.getAmount().add(debitRecord.getGoingAmt()));
            }
        }
        return basicDebitBatchDetails;
    }


    private List<BasicDebitBatch> generateDebitBatch(List<BasicDebitRecord> basicDebitRecordList, Date batchDate){

        /**  待扣款数据结构化 by ZC.GUO  **/
        Map<String,List<BasicDebitRecord>> debitRecordMap = this.dealDebitRecordList(basicDebitRecordList);

        /**  生成批次明细 by ZC.GUO  **/
        List<BasicDebitBatchDetails> debitBatchDetailsList = this.summaryBatchDetail(debitRecordMap,batchDate);

        /**  批次明细结构化 by ZC.GUO  **/
        Map<String,List<BasicDebitBatchDetails>> batchDetailMap = this.dealDebitDetailList(debitBatchDetailsList);

        /**  生成批次 by ZC.GUO  **/
        List<BasicDebitBatch> debitBatchList = this.summaryBatch(batchDetailMap);

        /**  更新扣款批次 by ZC.GUO  **/
        if (CollectionUtils.isNotEmpty(debitBatchList)){
            this.updateBatchById(debitBatchList);
        }

        /**  更新扣款批次明细 by ZC.GUO  **/
        if(CollectionUtils.isNotEmpty(debitBatchDetailsList)){
            basicDebitBatchDetailsService.saveBatch(debitBatchDetailsList);
            /**  分别更新待扣款数据 by ZC.GUO  **/
            for (BasicDebitBatchDetails batchDetails:debitBatchDetailsList){
                List<BasicDebitRecord> debitRecordList = debitRecordMap.get(batchDetails.getContractNo());
                for (BasicDebitRecord debitRecord:debitRecordList){
                    /**  待扣款数据更新
                     *   正在扣款金额 = 正在扣款金额+（待扣款金额-扣款成功金额-正在扣款金额）= 待扣款金额-扣款成功金额
                     * **/
                    debitRecord.setGoingAmt(debitRecord.getReadyAmt().subtract(debitRecord.getSucceedAmt()));
                    debitRecord.setDebitStatus(DebitStatusEnum.debiting);
                    debitRecord.setBatchId(batchDetails.getBatchId());
                    /**  使用乐观锁更新数据  **/
                    basicDebitRecordService.updateDebitRecordPrepare(debitRecord);
                }
            }
        }

        return debitBatchList;

    }

    @Override
    public Integer generateDebitBatchByList(List<BasicDebitRecord> basicDebitRecordList, Date batchDate){

        /**  待扣款数据结构化 by ZC.GUO  **/
        Map<String,List<BasicDebitRecord>> debitRecordMap = this.dealDebitRecordList(basicDebitRecordList);

        /**  生成批次明细 by ZC.GUO  **/
        List<BasicDebitBatchDetails> debitBatchDetailsList = this.summaryBatchDetail(debitRecordMap,batchDate);

        /**  批次明细结构化 by ZC.GUO  **/
        Map<String,List<BasicDebitBatchDetails>> batchDetailMap = this.dealDebitDetailList(debitBatchDetailsList);

        /**  生成批次 by ZC.GUO  **/
        List<BasicDebitBatch> debitBatchList = this.summaryBatch(batchDetailMap);

        /**  更新扣款批次 by ZC.GUO  **/
        if (CollectionUtils.isNotEmpty(debitBatchList)){
            this.updateBatchById(debitBatchList);
        }

        /**  更新扣款批次明细 by ZC.GUO  **/
        if(CollectionUtils.isNotEmpty(debitBatchDetailsList)){
            basicDebitBatchDetailsService.saveBatch(debitBatchDetailsList);
            /**  分别更新待扣款数据 by ZC.GUO  **/
            for (BasicDebitBatchDetails batchDetails:debitBatchDetailsList){
                List<BasicDebitRecord> debitRecordList = debitRecordMap.get(batchDetails.getContractNo());
                for (BasicDebitRecord debitRecord:debitRecordList){
                    /**  待扣款数据更新
                     *   正在扣款金额 = 正在扣款金额+（待扣款金额-扣款成功金额-正在扣款金额）= 待扣款金额-扣款成功金额
                     * **/
                    debitRecord.setGoingAmt(debitRecord.getReadyAmt().subtract(debitRecord.getSucceedAmt()));
                    debitRecord.setDebitStatus(DebitStatusEnum.debiting);
                    debitRecord.setBatchId(batchDetails.getBatchId());
                    /**  使用乐观锁更新数据  **/
                    basicDebitRecordService.updateDebitRecordPrepare(debitRecord);
                }
            }
        }

        return debitBatchList.size();

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deleteDebitBatch(BasicDebitBatch debitBatch) {

        if (ObjectUtils.isNotEmpty(debitBatch)){
            if (!(BatchStatusEnum.WAIT_SEND.equals(debitBatch.getBatchStatus())||BatchStatusEnum.FAIL_SEND.equals(debitBatch.getBatchStatus()))){
                return "该批次不可删除，请检查发送状态";
            }

            /**  删除批次明细 by ZC.GUO  **/
            basicDebitBatchDetailsService.remove(Wrappers.<BasicDebitBatchDetails>update().lambda()
                    .eq(BasicDebitBatchDetails::getBatchId,debitBatch.getId())
            );

            /**  更新待扣款数据 by ZC.GUO  **/
            basicDebitRecordService.update(Wrappers.<BasicDebitRecord>update().lambda()
                    .eq(BasicDebitRecord::getBatchId,debitBatch.getId())
                    .set(BasicDebitRecord::getBatchId,null)
                    .set(BasicDebitRecord::getDebitStatus,DebitStatusEnum.mayDebit)
                    .set(BasicDebitRecord::getGoingAmt,BigDecimal.ZERO)
            );
            /**  删除扣款批次 by ZC.GUO  **/
            this.removeById(debitBatch.getId());
            return "扣款批次删除成功";
        }else{
            return "找不到该批次";
        }
    }

    @Override
    public boolean lockOrUnlockBatch(BasicDebitBatch basicDebitBatch) {

        int count = baseMapper
                .updateWhenOperateDebitBatch(basicDebitBatch.getIsOperating(),basicDebitBatch.getId());
        if(count == 0) {
            log.info("乐观锁生效，扣款批次更新失败，id:[{}]", new Object[]{basicDebitBatch.getId()});
            return false;
        }else{
            return true;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void scanAndDealPrepaymentDebitOrder() {
        /**  查询所有的不可扣款的提前还款扣款指令 by ZC.GUO  **/
        List<BasicDebitRecord> prepaymentDebitRecordList = basicDebitRecordService.list(Wrappers.<BasicDebitRecord>query().lambda()
                .eq(BasicDebitRecord::getFeeType,FeeTypeEnum.advanceSettle)
                .eq(BasicDebitRecord::getDebitStatus,DebitStatusEnum.notMayDebit)
        );
        if (EmptyUtils.isNotEmpty(prepaymentDebitRecordList)){
            for (BasicDebitRecord prepaymentDebitRecord:prepaymentDebitRecordList){
                List<BasicDebitRecord> debitRecordList = basicDebitRecordService.list(Wrappers.<BasicDebitRecord>query().lambda()
                        .eq(BasicDebitRecord::getContractNo,prepaymentDebitRecord.getContractNo())
                        .isNotNull(BasicDebitRecord::getBatchId)
                        .ne(BasicDebitRecord::getId,prepaymentDebitRecord.getId())
                );
                /**  该合同没有正在扣款中的扣款指令 by ZC.GUO  **/
                if (EmptyUtils.isEmpty(debitRecordList)){
                    debitRecordList = basicDebitRecordService.list(Wrappers.<BasicDebitRecord>query().lambda()
                            .eq(BasicDebitRecord::getContractNo,prepaymentDebitRecord.getContractNo())
                            .ne(BasicDebitRecord::getId,prepaymentDebitRecord.getId())
                    );
                    if (EmptyUtils.isNotEmpty(debitRecordList)){
                        boolean isSuccess = false;
                        for (BasicDebitRecord debitRecord:debitRecordList){
                            if (debitRecord.getSucceedAmt().compareTo(BigDecimal.ZERO) > 0){
                                isSuccess = true;
                            }
                        }
                        /**  有成功扣款金额 by ZC.GUO  **/
                        if (isSuccess){
                            /**  提前结清报价失效 by ZC.GUO  **/
                            custChangeFeign.prepaymentRecordInvalid(prepaymentDebitRecord.getContractNo());
                            /**  本提前结清扣款指令删除 by ZC.GUO  **/
                            basicDebitRecordService.removeById(prepaymentDebitRecord.getId());

                        }
                        /**  没有成功金额 by ZC.GUO  **/
                        else{
                            /**  所有扣款指令归档 by ZC.GUO  **/
                            for (BasicDebitRecord debitRecord:debitRecordList){
                                BasicDebitRecordHistory debitRecordHistory = new BasicDebitRecordHistory();
                                BeanUtils.copyProperties(debitRecord,debitRecordHistory);
                                debitRecordHistory.setId(null);
                                debitRecordHistory.setStoreDate(Calendar.getInstance().getTime());
                                basicDebitRecordService.removeById(debitRecord.getId());
                                basicDebitRecordHistoryService.save(debitRecordHistory);
                            }
                            /**  本提前结清扣款指令生效 by ZC.GUO  **/
                            prepaymentDebitRecord.setDebitStatus(DebitStatusEnum.mayDebit);
                            basicDebitRecordService.updateById(prepaymentDebitRecord);
                        }
                    }
                    /**  除本提前结清扣款指令外不存在其他指令 by ZC.GUO  **/
                    else{
                        /**  本提前结清扣款指令生效 by ZC.GUO  **/
                        prepaymentDebitRecord.setDebitStatus(DebitStatusEnum.mayDebit);
                        basicDebitRecordService.updateById(prepaymentDebitRecord);
                    }
                }
            }
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String sendDebitBatch(BasicDebitBatch debitBatch,DebitModeEnum debitModeEnum) {
        if (ObjectUtils.isNotEmpty(debitBatch)){
            if (!(BatchStatusEnum.WAIT_SEND.equals(debitBatch.getBatchStatus())||BatchStatusEnum.FAIL_SEND.equals(debitBatch.getBatchStatus()))){
                return "该批次不可发送，请检查发送状态";
            }
            /**  查询批次明细 by ZC.GUO  **/
            List<BasicDebitBatchDetails> debitBatchDetailsList = basicDebitBatchDetailsService.list(Wrappers.<BasicDebitBatchDetails>query().lambda()
                    .eq(BasicDebitBatchDetails::getBatchId,debitBatch.getId())
                    .orderByAsc(BasicDebitBatchDetails::getContractNo)
            );

            /**  拼装报文体 by ZC.GUO  **/
            RecBatchApplyDTO recBatchApplyDTO = new RecBatchApplyDTO();

            /**  扣款银行通道 by ZC.GUO  **/

            String chlCd = null;
            Map<String, List<DicDataDto>> dicMap = DicHelper.getDicMaps("mappingBank");
            List<DicDataDto> dicList=dicMap.get("mappingBank");
            for (DicDataDto dto : dicList){
                if(dto.getValue().equals(debitBatch.getDeductBank())){
                    chlCd = dto.getTitle();
                }
            }
            Assert.isTrue(!org.springframework.util.ObjectUtils.isEmpty(chlCd),"无此银行代码的通道[{}]",debitBatch.getDeductBank());
            recBatchApplyDTO.setChlCd(chlCd);

            if (CollectionUtils.isEmpty(debitBatchDetailsList)){
                return "批次明细为空，不可发送";
            }else{
                List<RecBatchApplyDTO.RecBatchListApplyDTO> data = new ArrayList<>();
                Integer seqNo = 1;
                Iterator<BasicDebitBatchDetails> iterator = debitBatchDetailsList.iterator();
                while (iterator.hasNext()){
                    RecBatchApplyDTO.RecBatchListApplyDTO single = recBatchApplyDTO.new RecBatchListApplyDTO();
                    single.setSeqNo(String.valueOf(seqNo));
                    BasicDebitBatchDetails debitBatchDetails = iterator.next();
                    debitBatchDetails.setSeqNo(seqNo);
                    debitBatchDetails.setStatus(DebitStatusEnum.noResult);
                    debitBatchDetails.setSendDate(Calendar.getInstance().getTime());

                    /**  0-银行卡； by ZC.GUO  **/
                    single.setPayAcctType("0");
                    single.setPayAcctNo(debitBatchDetails.getDebitAccount());
                    single.setPayAcctNm(debitBatchDetails.getDebitAccountName());

                    /**  未收集客户还款卡开户分支行，使用总行名称代替 by ZC.GUO  **/
                    Map<String, List<DicDataDto>> map = DicHelper.getDicMaps("bankCode");
                    List<DicDataDto> list=map.get("bankCode");
                    for (DicDataDto dto : list){
                        if(dto.getValue().equals(debitBatchDetails.getDebitSignBank())){
                            single.setPayAcctBkNm(dto.getTitle());
                        }
                    }
                    single.setPayNo(debitBatchDetails.getDebitSignCode());
                    single.setCurrencyType("CNY");
                    single.setPayAmount(debitBatchDetails.getAmount().toString());
                    single.setCardType("01");
                    single.setCardNo(debitBatchDetails.getDebitCertNo());
                    single.setTel(debitBatchDetails.getDebitCardPhone());
                    single.setContractNo(debitBatchDetails.getContractNo());
                    single.setRmk("收取本息");

                    /**  车架号和申请编号 by ZC.GUO  **/
                    BasicMainInfo mainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>query().lambda()
                            .eq(BasicMainInfo::getContractNo,debitBatchDetails.getContractNo())
                    );
                    if (EmptyUtils.isNotEmpty(mainInfo)){
                        single.setApplicationNo(mainInfo.getApplyNo());
                    }
                    BasicCarDetails carDetails = basicCarDetailsService.getOne(Wrappers.<BasicCarDetails>query().lambda()
                            .eq(BasicCarDetails::getContractNo,debitBatchDetails.getContractNo()),false);
                    if (EmptyUtils.isNotEmpty(carDetails)){
                        single.setFrameNumber(carDetails.getCarVin());
                    }
                    data.add(single);


                    seqNo += 1;
                }
                recBatchApplyDTO.setData(data);

                /**  更新批次明细 by ZC.GUO  **/
                basicDebitBatchDetailsService.updateBatchById(debitBatchDetailsList);

            }

            /**  新增接口记录 by ZC.GUO  **/
            BasicDebitInterfaceRecord debitInterfaceRecord = new BasicDebitInterfaceRecord();

            /**  发送报文 by ZC.GUO  **/
            EasypassRsponseBean easypassRsponseBean = iEasypassProcessService.recBatchApply(recBatchApplyDTO);


            if(!AfsEnumUtil.key(RsponseStatusEnum.HEAD_SUCCESS).equals(easypassRsponseBean.getResultCode())){

                log.info("发送睿易通失败，批次号码为：{}",debitBatch.getBatchNo());
                /**  更新扣款批次 by ZC.GUO  **/
                debitBatch.setBatchStatus(BatchStatusEnum.FAIL_SEND);
                debitBatch.setFeedbackMsg(easypassRsponseBean.getResultDesc());
                this.updateById(debitBatch);

                /**  新增接口记录 by ZC.GUO  **/
                debitInterfaceRecord.setResponseTime(Calendar.getInstance().getTime());
                debitInterfaceRecord.setRequestResult(RequestResultEnum.sendException);
                debitInterfaceRecord.setBatchId(debitBatch.getId());
                debitInterfaceRecord.setInterfaceType(InterfaceTypeEnum.client);
                debitInterfaceRecord.setInterfaceCode(InterfaceCodeEnum.batchRequest);
                debitInterfaceRecord.setInterfaceName("代扣申请_批量");
                basicDebitInterfaceRecordService.save(debitInterfaceRecord);
                return "发送睿易通失败";
            }else{
                log.info("发送睿易通成功，批次号码为：{}",debitBatch.getBatchNo());
                /**  更新扣款批次 by ZC.GUO  **/
                debitBatch.setDebitMode(debitModeEnum);
                debitBatch.setBatchStatus(BatchStatusEnum.SUCCESS_SEND);
                debitBatch.setGoingCount(debitBatch.getCount());
                debitBatch.setGoingAmt(debitBatch.getAmount());
                debitBatch.setMsgid(easypassRsponseBean.getMsgid());
                debitBatch.setFeedbackMsg(easypassRsponseBean.getResultDesc());
                this.updateById(debitBatch);

                /**  新增接口记录 by ZC.GUO  **/
                debitInterfaceRecord.setResponseTime(Calendar.getInstance().getTime());
                debitInterfaceRecord.setRequestResult(RequestResultEnum.sendSuccess);
                debitInterfaceRecord.setBatchId(debitBatch.getId());
                debitInterfaceRecord.setInterfaceType(InterfaceTypeEnum.client);
                debitInterfaceRecord.setInterfaceCode(InterfaceCodeEnum.batchRequest);
                debitInterfaceRecord.setInterfaceName("代扣申请_批量");
                basicDebitInterfaceRecordService.save(debitInterfaceRecord);

                /**  创建扣款历史记录 by ZC.GUO  **/
                List<BasicDebitHistory> debitHistoryList = new ArrayList<>();
                List<BasicDebitRecord> debitRecordList = basicDebitRecordService.list(Wrappers.<BasicDebitRecord>query().lambda()
                        .eq(BasicDebitRecord::getBatchId,debitBatch.getId())
                );
                if (CollectionUtils.isNotEmpty(debitRecordList)){
                    debitRecordList.forEach(debitRecord -> {
                        BasicDebitHistory debitHistory = new BasicDebitHistory();
                        debitHistory.setBatchId(debitBatch.getId());
                        debitHistory.setRecordId(debitRecord.getId());
                        debitHistory.setContractNo(debitRecord.getContractNo());
                        debitHistory.setFeeType(debitRecord.getFeeType());
                        debitHistory.setSendTime(Calendar.getInstance().getTime());
                        debitHistory.setReadyAmt(debitRecord.getReadyAmt());
                        debitHistory.setPlanDate(debitRecord.getPlanDate());
                        debitHistory.setTermNo(debitRecord.getTermNo());
                        debitHistory.setDebitAmt(debitRecord.getGoingAmt());
                        debitHistoryList.add(debitHistory);
                    });
                    basicDebitHistoryService.saveBatch(debitHistoryList);
                }
                return "扣款批次发送成功";
            }

        }else{
            return "找不到该批次";
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void queryDebitBatchResult(BasicDebitBatch debitBatch, Date batchDate) {

        if (EmptyUtils.isNotEmpty(debitBatch)){
        BasicDebitInterfaceRecord debitInterfaceRecord = new BasicDebitInterfaceRecord();
        debitInterfaceRecord.setRequestTime(Calendar.getInstance().getTime());
        /**  请求睿易通接口 by ZC.GUO  **/
        EasypassRsponseBean<RecResultQryDTO> easypassResponseBean = iEasypassProcessService.recResultQry(debitBatch.getMsgid());

        if(!AfsEnumUtil.key(RsponseStatusEnum.HEAD_SUCCESS).equals(easypassResponseBean.getResultCode())){
            /**  接口记录 by ZC.GUO  **/
            debitInterfaceRecord.setResponseTime(Calendar.getInstance().getTime());
            debitInterfaceRecord.setRequestResult(RequestResultEnum.sendException);
            debitInterfaceRecord.setBatchId(debitBatch.getId());
            debitInterfaceRecord.setInterfaceType(InterfaceTypeEnum.client);
            debitInterfaceRecord.setInterfaceCode(InterfaceCodeEnum.batchFeedback);
            debitInterfaceRecord.setInterfaceName("代扣申请结果查询");
            basicDebitInterfaceRecordService.save(debitInterfaceRecord);
        }else{
            /**  接口记录 by ZC.GUO  **/
            debitInterfaceRecord.setResponseTime(Calendar.getInstance().getTime());
            debitInterfaceRecord.setRequestResult(RequestResultEnum.sendSuccess);
            debitInterfaceRecord.setBatchId(debitBatch.getId());
            debitInterfaceRecord.setInterfaceType(InterfaceTypeEnum.client);
            debitInterfaceRecord.setInterfaceCode(InterfaceCodeEnum.batchFeedback);
            debitInterfaceRecord.setInterfaceName("代扣申请结果查询");
            basicDebitInterfaceRecordService.save(debitInterfaceRecord);

            /**  by ZC.GUO  **/
            RecResultQryDTO recResultQryDTO = easypassResponseBean.getBody();
            this.handleDebitResultCallBack(recResultQryDTO,debitBatch.getMsgid(),batchDate);
        }
        }
    }


    /**
     *
     * <p>Description: </p>
     *
     * @param debitBatch
     * @param batchDetails
     * @return
     */
    private BasicDebitBatch updateBatch(BasicDebitBatch debitBatch,BasicDebitBatchDetails batchDetails){
        /**  批次扣款笔数 by ZC.GUO  **/
        debitBatch.setCount(debitBatch.getCount() + 1);
        /**  批次扣款总额  **/
        debitBatch.setAmount(debitBatch.getAmount().add(batchDetails.getAmount()));
        return debitBatch;
    }

    /**
     *
     * <p>Description: 扣款批次数据初始化</p>
     *
     * @param debitBatch
     * @param debitBatchDetails
     * @return
     */
    private BasicDebitBatch initBatch(BasicDebitBatch debitBatch,BasicDebitBatchDetails debitBatchDetails){
        /**  生成批次号  **/
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Long seqNo = afsSequenceGenerator.genNext("DEBIT_BATCH",dateFormat.format(Calendar.getInstance().getTime()));
        String seqStr = StringUtils.leftPad(seqNo.toString(),4,"0");
        String batchNo = "BATCH" + dateFormat.format(Calendar.getInstance().getTime()) + seqStr;

        debitBatch.setBatchNo(batchNo);
        debitBatch.setDeductBank(debitBatchDetails.getDebitSignBank());
        debitBatch.setBatchStatus(BatchStatusEnum.WAIT_SEND);
        debitBatch.setCount(0);
        debitBatch.setAmount(BigDecimal.ZERO);
        debitBatch.setSuccessCount(0);
        debitBatch.setSuccessAmt(BigDecimal.ZERO);
        debitBatch.setFaildCount(0);
        debitBatch.setFaildAmt(BigDecimal.ZERO);
        debitBatch.setGoingCount(0);
        debitBatch.setGoingAmt(BigDecimal.ZERO);
        debitBatch.setExeceptCount(0);
        debitBatch.setExeceptAmt(BigDecimal.ZERO);
        debitBatch.setIsOperating(YesOrNoEnum.no);
        return  debitBatch;
    }

    /**
     *
     * <p>Description: 扣款批次明细初始化</p>
     *
     * @param debitBatchDetails
     * @param debitRecord
     * @return
     */
    private BasicDebitBatchDetails initBatchDetail(BasicDebitBatchDetails debitBatchDetails,BasicDebitRecord debitRecord){
        /**  合同基本信息  **/
        BasicMainInfo mainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>query().lambda()
                .eq(BasicMainInfo::getContractNo,debitRecord.getContractNo())
        );

        if (ObjectUtils.isNotEmpty(mainInfo)){
            debitBatchDetails.setApplyNo(mainInfo.getApplyNo());
            debitBatchDetails.setContractStatus(mainInfo.getContractStatus());
        }
        debitBatchDetails.setContractNo(debitRecord.getContractNo());

        /**  扣款信息  **/
        debitBatchDetails.setAmount(BigDecimal.ZERO);
        debitBatchDetails.setStatus(DebitStatusEnum.noResult);
        debitBatchDetails.setDebitSignBank(debitRecord.getDebitSignBank());
        debitBatchDetails.setDebitSignCode(debitRecord.getDebitSignCode());
        debitBatchDetails.setDebitEbankCode(debitRecord.getDebitEbankCode());
        debitBatchDetails.setDebitAccount(debitRecord.getDebitAccount());
        debitBatchDetails.setDebitAccountName(debitRecord.getDebitAccountName());
        debitBatchDetails.setDebitCardPhone(debitRecord.getDebitCardPhone());
        debitBatchDetails.setDebitCertNo(debitRecord.getDebitCertNo());
        debitBatchDetails.setDebitBankBranch(debitRecord.getDebitBankBranch());

        return debitBatchDetails;
    }
    /**
     * Description: 批次明细数据累加更新
     *
     * @param debitBatchDetails
     * @param debitRecord
     * @return
     */
    private BasicDebitBatchDetails updateBatchDetail(
            BasicDebitBatchDetails debitBatchDetails, BasicDebitRecord debitRecord) {
        /**  可扣款金额为待扣款金额-已扣款成功金额-正在扣款金额  **/
        debitBatchDetails.setAmount(debitBatchDetails.getAmount().add(debitRecord.getReadyAmt().subtract(debitRecord.getSucceedAmt()).subtract(debitRecord.getGoingAmt())));
        return debitBatchDetails;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean handleDebitResultCallBack(RecResultQryDTO recResultQryDTO,String msgId, Date batchDate) {
        BasicDebitInterfaceRecord debitInterfaceRecord = new BasicDebitInterfaceRecord();
        debitInterfaceRecord.setResponseTime(Calendar.getInstance().getTime());
        /**  获取扣款批次 by ZC.GUO  **/
        List<BatchStatusEnum> statusList = new ArrayList<>();
        statusList.add(BatchStatusEnum.WAIT_SEND);
        statusList.add(BatchStatusEnum.SENDING);
        statusList.add(BatchStatusEnum.FAIL_SEND);
        BasicDebitBatch debitBatch = this.getOne(Wrappers.<BasicDebitBatch>query().lambda()
                .eq(BasicDebitBatch::getMsgid,msgId)
                .notIn(BasicDebitBatch::getBatchStatus,statusList)
        );

        BatchStatusEnum oldStatus = debitBatch.getBatchStatus();

        if (ObjectUtils.isNotEmpty(debitBatch)){
            debitInterfaceRecord.setBatchId(debitBatch.getId());
            List<RecResultQryDTO.RecResultQryListDTO> status  = recResultQryDTO.getStatus();
            if(CollectionUtils.isNotEmpty(status)){

                debitBatch.setGoingCount(0);
                debitBatch.setGoingAmt(BigDecimal.ZERO);
                debitBatch.setBatchStatus(BatchStatusEnum.SUCCESS_FEEDBACK);

                status.forEach(detailStatus -> {
                    BasicDebitBatchDetails debitBatchDetails = basicDebitBatchDetailsService.getOne(Wrappers.<BasicDebitBatchDetails>query().lambda()
                            .eq(BasicDebitBatchDetails::getBatchId,debitBatch.getId())
                            .eq(BasicDebitBatchDetails::getSeqNo,detailStatus.getSeqNo())
                    );
                    if(debitBatchDetails != null){
                        /**  已经进行过成功或者失败处理的不再处理 by ZC.GUO  **/
                        if(!(DebitStatusEnum.failDebit.equals(debitBatchDetails.getStatus())||DebitStatusEnum.successDebit.equals(debitBatchDetails.getStatus()))){
                            /**  扣款成功 by ZC.GUO  **/
                            if (AfsEnumUtil.key(RsponseStatusEnum.SUCCESS).equals(detailStatus.getStatus())){
                                basicDebitBatchDetailsService.debitSuccess(debitBatch,debitBatchDetails,detailStatus.getMessage(),detailStatus.getCreditAccount(),detailStatus.getBankName(),detailStatus.getOpeningBankName(),batchDate);
                                debitBatch.setSuccessAmt(debitBatch.getSuccessAmt().add(debitBatchDetails.getAmount()));
                                debitBatch.setSuccessCount(debitBatch.getSuccessCount()+1);
                            }
                            /**  扣款失败 by ZC.GUO  **/
                            else if (AfsEnumUtil.key(RsponseStatusEnum.FAIL).equals(detailStatus.getStatus())){
                                basicDebitBatchDetailsService.debitFailed(debitBatch,debitBatchDetails,detailStatus.getMessage(),batchDate);
                                debitBatch.setFaildAmt(debitBatch.getFaildAmt().add(debitBatchDetails.getAmount()));
                                debitBatch.setFaildCount(debitBatch.getFaildCount()+1);
                            }
                            /**  暂无扣款结果 by ZC.GUO  **/
                            else if (AfsEnumUtil.key(RsponseStatusEnum.EXECING).equals(detailStatus.getStatus())){
                                basicDebitBatchDetailsService.debitNoResult(debitBatchDetails);
                                debitBatch.setGoingAmt(debitBatch.getGoingAmt().add(debitBatchDetails.getAmount()));
                                debitBatch.setGoingCount(debitBatch.getGoingCount()+1);
                                /**  只要有一条没结果，整个批次状态不更新 by ZC.GUO  **/
                                debitBatch.setBatchStatus(oldStatus);
                            }
                        }
                    }

                });
            }
        }else{
            log.warn("代扣结果查询接口错误，交易流水号错误，无此交易,流水号：{}",msgId);
            return false;
        }
        /**  新增扣款接口记录 by ZC.GUO  **/
        debitInterfaceRecord.setInterfaceType(InterfaceTypeEnum.server);
        debitInterfaceRecord.setInterfaceCode(InterfaceCodeEnum.batchCallback);
        debitInterfaceRecord.setInterfaceName("代收付处理结果通知");
        debitInterfaceRecord.setResponseTime(Calendar.getInstance().getTime());
        debitInterfaceRecord.setRequestResult(RequestResultEnum.sendSuccess);
        debitInterfaceRecord.setResponseResult(ResponseResultEnum.responeSuccess);
        basicDebitInterfaceRecordService.save(debitInterfaceRecord);

        /**  更新扣款批次 by ZC.GUO  **/
        this.updateById(debitBatch);
        return true;
    }

}
